﻿(function (window, $) {

    // 保存Hub注册信息
    var listeners = {};

    //全局signalr会话ID
    var respId = null;
    var signalrConnection = null;

    var wap = {

        // 版本号
        version: '1.0.0',

        // 通用代码
        common: {

            customURIScheme: function (scheme) {
                /// <summary>
                /// 用于打开外部引用程序
                /// </summary>
                //alert(scheme);
                location.replace(scheme)
            },

            camera: function (id, workId, workInfo, productType) {
                /// <summary>
                /// 打开高拍仪
                /// </summary>
                /// <param name="id">会话Id</param>
                /// <param name="type">设备类型</param>

                var URI_PREX_CAMERA = 'WAP.Client:-m=MODULE_CAMERA;-p={\\"ConnectionId\\":\\"',
                    URI_PREX_Jaeyi = 'WAP.Client:-m=MODULE_Jaeyi,--p={\\"ConnectionId\\":\\"';

                var url = URI_PREX_CAMERA;

                if (!productType) {
                    if (productType === 'Jaeyi') {
                        url = URI_PREX_Jaeyi;
                    }
                }

                url = url + id + '\\",\\"workId\\":\\"';
                url = url + workId + '\\",\\"workInfo\\":\\"';
                url = url + workInfo + '\\"}';

                this.customURIScheme(url);
            },

            upload: function (id, workId, workInfo) {
                /// <summary>
                /// 上传
                /// </summary>
                /// <param name="id">会话Id</param>

                var URI_PREX_UPLOAD = 'WAP.Client:-m=MODULE_UPLOAD;-p={\\"ConnectionId\\":\\"';
                var url = URI_PREX_UPLOAD + id + '\\",\\"workId\\":\\"';
                url = url + workId + '\\",\\"workInfo\\":\\"';
                url = url + workInfo + '\\"}';
                this.customURIScheme(url);
            },

            print: function (template, ps) {
                /// <summary>
                /// 打印 
                /// 
                /// <example>
                /// [{ key: 'ids' , value: '1,2,3' }, { key: 'subcom', value: '00' }]
                /// </example>
                /// 
                /// </summary>
                /// <param name="template" type="String">模板Id</param>
                /// <param name="ps" type="Array">参数列表</param>

                var URI_PREX_PRINT = 'WAP.Client:-m=MODULE_PRINT;';

                var url = '', tmp = [];
                var uId = 1;

                tmp.push(URI_PREX_PRINT, '-p={\\"Template\\":\\"', template,
                    '\\",\\"UserId\\":\\"', uId,
                    '\\",\\"Command\\":\\"PRINT\\",',
                    '\\"Parameters\\":{');

                // 追加
                var param = '';
                if (ps && ps.length && ps.length > 0) {
                    for (var i = 0; i < ps.length; i++) {
                        var item = ps[i];
                        tmp.push('\\"' + item.key + '\\":\\"', item.value, '\\"');
                        if (i < ps.length - 1) tmp.push(',');
                    }

                    tmp.push('}};--verbos');

                } else {
                    tmp.push('};--verbos');
                }
                
                url = tmp.join('');
                
                this.customURIScheme(url);
            },
            printjx: function (template, ps) {
                /// <summary>
                /// 机械表账单打印 
                /// 
                /// <example>
                /// [{ key: 'ids' , value: '1,2,3' }, { key: 'subcom', value: '00' }]
                /// </example>
                /// 
                /// </summary>
                /// <param name="template" type="String">模板Id</param>
                /// <param name="ps" type="Array">参数列表</param>

                var URI_PREX_PRINT = 'WAP.Client:-m=MODULE_PRINT;';

                var url = '', tmp = [];
                var uId = 1;

                tmp.push(URI_PREX_PRINT, '-p={\\"Template\\":\\"', template,
                    '\\",\\"UserId\\":\\"', uId,
                    '\\",\\"Command\\":\\"JIXIE\\",',
                    '\\"Parameters\\":{');

                // 追加
                var param = '';
                if (ps && ps.length && ps.length > 0) {
                    for (var i = 0; i < ps.length; i++) {
                        var item = ps[i];
                        //decodeURI(
                        //alert(item.key);
                        //alert(item.value);
                        //alert(decodeURI(item.value));
                        tmp.push('\\"' + item.key + '\\":\\"', item.value, '\\"');
                        if (i < ps.length - 1) tmp.push(',');
                    }

                    tmp.push('}};--verbos');

                } else {
                    tmp.push('};--verbos');
                }

                url = tmp.join('');
                //alert(url);
                this.customURIScheme(url);
            },

            preview: function (template, ps) {
                /// <summary>
                /// 打印 预览
                /// 
                /// <example>
                /// [{ key: 'ids' , value: '1,2,3' }, { key: 'subcom', value: '00' }]
                /// </example>
                /// 
                /// </summary>
                /// <param name="template" type="String">模板Id</param>
                /// <param name="ps" type="Array">参数列表</param>

                var URI_PREX_PRINT = 'WAP.Client:-m=MODULE_PRINT;';

                var url = '', tmp = [];
                var uId = 1;

                tmp.push(URI_PREX_PRINT, '-p={\\"Template\\":\\"', template,
                    '\\",\\"UserId\\":\\"', uId,
                    '\\",\\"Command\\":\\"PREVIEW\\",',
                    '\\"Parameters\\":{');

                // 追加
                var param = '';
                if (ps && ps.length && ps.length > 0) {
                    for (var i = 0; i < ps.length; i++) {
                        var item = ps[i];
                        tmp.push('\\"' + item.key + '\\":\\"', item.value, '\\"');
                        if (i < ps.length - 1) tmp.push(',');
                    }

                    tmp.push('}};--verbos');

                } else {
                    tmp.push('};--verbos');
                }

                url = tmp.join('');
                this.customURIScheme(url);
            },
            login: function (template, ps) {
                
                /// <summary>
                /// 登录验证
                /// 
                /// <example>
                /// [{ key: 'ids' , value: '1,2,3' }, { key: 'subcom', value: '00' }]
                /// </example>
                /// 
                /// </summary>
                /// <param name="template" type="String">模板Id</param>
                /// <param name="ps" type="Array">参数列表</param>

                var URI_PREX_PRINT = 'WAP.Client:-m=MODULE_PRINT;';

                var url = '', tmp = [];
                var uId = 1;

                tmp.push(URI_PREX_PRINT, '-p={\\"Template\\":\\"', template,
                    '\\",\\"UserId\\":\\"', uId,
                    '\\",\\"Command\\":\\"LOGIN\\",',
                    '\\"Parameters\\":{');

                // 追加
                var param = '';
                if (ps && ps.length && ps.length > 0) {
                    for (var i = 0; i < ps.length; i++) {
                        var item = ps[i];
                        tmp.push('\\"' + item.key + '\\":\\"', item.value, '\\"');
                        if (i < ps.length - 1) tmp.push(',');
                    }

                    tmp.push('}};--verbos');

                } else {
                    tmp.push('};--verbos');
                }
                
                url = tmp.join('');
                
                this.customURIScheme(url);
            },
            /// <summary>
            /// 参数存储,数据库存储返回主键
            /// 
            /// <example>
            /// 1,2,3,8,6,1,0,5,454,13521
            /// </example>
            /// 
            /// </summary>  
            /// <param name="ps" type="string">参数列表</param>
            argsSave: function (ps) {
                return App.$post(window.URI.Common.printRequest, JSON.stringify(ps));
            },
            evaluate: function (id, workId, workInfo) {
                /// <summary>
                /// 评价器
                /// </summary>
                var URI_PREX_EVALUATE = 'WAP.Client:-m=MODULE_EVALUATE;-p={\\"ConnectionId\\":\\"';
                var url = URI_PREX_EVALUATE + id + '\\",\\"workId\\":\\"';
                url = url + workId + '\\",\\"workInfo\\":\\"';
                url = url + workInfo + '\\"}';
                this.customURIScheme(url);
            }
        },

        signalr: {

            connect: function (url, defer) {
                /// <summary>
                /// 创建signalr连接
                /// </summary>
                /// <param name="url">Signalr服务地址</param>
                /// <param name="defer">连接后回调对象</param>

                var _url = url + '/signalr';

                // 加载signalr中的hub脚本
                var request = $.ajax({
                    url: _url + '/hubs',
                    dataType: 'script'
                });

                request.done(function () {

                    // 初始化hub
                    $.connection.hub.url = _url;

                    // 注册已经注册的监听器
                    $.each(listeners, function (key, funcs) {
                        var hub = $.connection[key];
                        if (hub && hub !== null) {
                            $.each(funcs, function (func, callbacks) {
                                if (callbacks.length == 1) {
                                    hub.client[func] = callbacks[0].callback;
                                } else {
                                    hub.client[func] = function (message) {
                                        $.each(callbacks, function (_, c) {
                                            c.callback(message);
                                        })
                                    }
                                }
                            });
                        }
                    });

                    var options = {
                        transport: ['webSockets', 'longPolling']
                    };

                    $.connection.hub
                        .start(options)
                        .done(function (response) {
                            if (defer) {
                                defer.resolve(response);
                            }
                        })
                        .fail(function (error) {
                            if (defer) {
                                defer.reject(error);
                            }
                        });

                });

                request.fail(function () {
                    wsdpPromptService.error('无法启动SignalR通知服务。', '系统错误');
                });
            },

            disconnect: function () {
                /// <summary>
                /// 断开与Signalr的连接
                /// </summary>

                var hub = $.connection.hub;
                if (hub && hub.stop) {
                    hub.stop();
                }
            },

            register: function (hub, func, callback, id) {
                /// <summary>
                /// 注册SignalR Hub服务
                /// </summary>
                /// <param name="hub">Hub名称</param>
                /// <param name="func">Hub方法名称</param>
                /// <param name="callback">回调函数</param>

                var _hub = listeners[hub];
                if (!_hub) {
                    _hub = {};
                    listeners[hub] = _hub;
                }

                var _func = _hub[func];
                if (!_func) {
                    _func = [];
                    _hub[func] = _func;
                }

                var flag = false;

                _func.forEach(function (item, index, array) {
                    if (item.id === id) {
                        flag = true;
                    }
                });

                if (!flag) {
                    _func.push({ hub: hub, func: func, callback: callback, id: id });
                }

            },

            unregister: function (hub, func, id) {
                var _hub = listeners[hub];
                if (_hub) {
                    var _func = _hub[func];
                    if (_func) {
                        _func.forEach(function (item, index, array) {
                            if (item.id === id) {
                                var removeIndex = index;
                                _func.splice(removeIndex, 1);
                            }
                        });

                    }
                }
            }
        },

        signalrNew: {
            init: function (url, hub, func, callback) {
                /// <summary>
                /// 创建signalr连接
                /// </summary>
                /// <param name="url">Signalr服务地址</param>
                /// <param name="defer">连接后回调对象</param>

                var _url = url + '/signalr';

                // 加载signalr中的hub脚本
                var request = $.ajax({
                    url: _url + '/hubs',
                    dataType: 'script'
                });

                request.done(function () {

                    // 初始化hub
                    $.connection.hub.url = _url;
                    $.connection[hub].client[func] = function (message) {
                        callback(message);
                    };

                    var options = {
                        transport: ['webSockets', 'longPolling']
                    };

                    $.connection.hub
                        .start(options)
                        .done(function (response) {
                            respId = response.id;
                            //if (defer) {
                            //    defer.resolve(response);
                            //}
                        })
                        .fail(function (error) {
                            //if (defer) {
                            //    defer.reject(error);
                            //}
                        });

                });

                request.fail(function () {
                    wsdpPromptService.error('无法启动SignalR通知服务。', '系统错误');
                });
            },

            getrespId: function () {
                return respId;
            }
        }
    }

    // 导出wap对象
    window.wap = wap;

})(window, $)
